package com.situ.mall.controller;

import com.situ.mall.mapper.UserMapper;
import com.situ.mall.pojo.User;
import com.situ.mall.pojo.query.UserQuery;
import com.situ.mall.service.IUserService;
import com.situ.mall.util.LayUITableResult;
import com.situ.mall.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/login")
    @ResponseBody
    public Result login(String username, String password, String code, HttpSession session) {
        //先验证验证码对不对，验证码不对，直接返回“验证码错误”
        String codeInSession = (String) session.getAttribute("codeInSession");
        if (!codeInSession.equalsIgnoreCase(code)) {
            return Result.error("验证码错误");
        }

        User user = userService.login(username, password);
        if (user == null) {
            return Result.error("用户名密码错误");
        } else {
            //把登录凭证放到Session
            session.setAttribute("user", user);
            return Result.ok("登录成功");
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/user/toLogin";
    }

    @RequestMapping("/add")
    @ResponseBody
    public Result add(User user) {
        userService.add(user);
        return Result.ok("添加成功");
    }

    @RequestMapping("/toAdd")
    public String toAdd() {
        return "user/add";
    }

    @RequestMapping("/deleteAll")
    @ResponseBody
    public Result deleteAll(Integer[] ids) {
        userService.deleteAll(ids);
        return Result.ok("删除成功");
    }

    @RequestMapping("/deleteById")
    @ResponseBody
    public Result deleteById(Integer id) {
        userService.deleteById(id);
        return Result.ok("删除成功");
    }

    @RequestMapping("/toList")
    public String toList() {
        return "user/list";
    }

    //http://layui.apixx.net/test/table/demo1.json.js?page=1&limit=10
    //http://127.0.0.1:8087/user/list?page=1&limit=10
    //http://localhost:8087/user/list?page=1&limit=10&username=zhangsan&email=ss
    @RequestMapping("/list")
    @ResponseBody
    public LayUITableResult list(UserQuery userQuery) {
        LayUITableResult layUITableResult = userService.list(userQuery);
        return layUITableResult;
    }

    /*@RequestMapping("/list")
    @ResponseBody
    public List<User> list(Integer id) {
        List<User> list = userService.list();
        return list;
    }*/
}
